<template>
  <div id="app">
    <el-header class="header">
      <div class="title">公租房租赁平台 - 房屋查询</div>
      <div class="auth-buttons">
        <p v-if="$store.state.isLogin">欢迎您，{{ this.$store.state.loginTenant.account }} |</p>
        <el-button
          v-if="!$store.state.isLogin"
          type="text"
          @click="$router.push('/login',() =>{},() =>{})"
          style="margin-top: 6px; margin-right: 10px"
        >登录</el-button>
        <el-button v-else type="text" @click="logout" style="margin-top: 6px; margin-right: 5px">登出</el-button>
        <el-popover placement="bottom" width="400" trigger="hover">
          <div>
            <h3 style="text-align: center; margin-top: 0px;">未读消息</h3>
            <p v-if="messages.length == 0" style="text-align: center; color:gray">暂无未读消息</p>
            <el-card v-for="message in messages" :key="message.id" style="margin-bottom: 10px">
              <i class="el-icon-info"></i>
              <span style="margin-left: 10px">
                <strong>{{ message.title }}</strong>
              </span>
              <p>{{ message.content }}</p>
            </el-card>
          </div>
          <el-badge
            v-if="$store.state.isLogin"
            slot="reference"
            :value="messages.length"
            class="item"
            style="margin-top: 10px; margin-right: 10px"
          >
            <el-button
              v-if="$store.state.isLogin"
              type="text"
              @click="$router.push('/message',() =>{},() =>{})"
            >消息中心</el-button>
          </el-badge>
        </el-popover>
        <el-button
          v-if="!$store.state.isLogin"
          type="text"
          @click="$router.push('/register',() =>{},() =>{})"
          style="margin-top: 6px; margin-right: 10px"
        >注册</el-button>
        <el-button
          v-else
          type="text"
          @click="$router.push('/userInfo',() =>{},() =>{})"
          style="margin-top: 6px; margin-right: 10px"
        >个人中心</el-button>
      </div>
    </el-header>
    <el-breadcrumb separator="/" class="breadcrumb">
      <el-breadcrumb-item :to="{ path: `/`}">首页</el-breadcrumb-item>
      <el-breadcrumb-item>房屋查询</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="navigation-card">
      <el-collapse accordion>
        <el-collapse-item title="筛选条件" name="1">
          <div v-for="(category, index) in categories" :key="index" class="category">
            <span>{{ category.name }}</span>
            <span style="margin-right: 10px">：</span>
            <span class="items">
              <a
                v-for="(item, idx) in category.items"
                :key="idx"
                href="#"
                @click="filterHouses(category.name, item)"
                :class="{ active: isActive(category.name, item) }"
              >{{ item }}</a>
            </span>
          </div>
        </el-collapse-item>
      </el-collapse>
    </el-card>
    <el-row :gutter="20" class="results">
      <el-col :span="6" v-for="item in houses" :key="item.id">
        <el-card :body-style="{ padding: '20px' }">
          <img :src="item.image" class="image" />
          <div style="padding: 14px;">
            <div class="bottom clearfix">
              <span>{{ item.name }}</span>
              <span style="float: right; padding: 3px 0; color: #f56c6c">{{ item.rent }}</span>
            </div>
            <div class="bottom clearfix">
              <p class="other">{{ item.other }}</p>
              <el-button
                @click="goToHouseDetail(item.areaName,item.communityName,item.roomNumber)"
                type="text"
                class="button"
              >查看详情</el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <div class="pagination-container">
      <el-pagination
        v-if="houses.length > 0"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[4, 8, 12, 16]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
      <div v-else style="text-align: center; margin-top: 20px;">
        <el-empty description="当前区域没有房屋信息"></el-empty>
      </div>
    </div>
    <el-backtop :visibility-height="10"></el-backtop>
  </div>
</template>

<script>
import store from "@/utils/storage";
export default {
  data() {
    return {
      categories: [
        { name: "省份", items: [] },
        { name: "城市", items: [] },
        { name: "区域", items: [] },
        { name: "小区", items: [] },
        { name: "户型", items: [] },
        { name: "面积", items: [] },
        { name: "租金", items: [] }
      ],
      houses: [],
      activeFilters: {},
      newItems: [],
      currentPage: 1,
      pageSize: 8,
      total: "",
      search: {},
      messages: []
    };
  },
  mounted() {
    this.getProvince();
    this.getMessages();
  },
  methods: {
    getMessages() {
      if (this.$store.state.isLogin) {
        this.$axios
          .post("message/get", {
            tenant: this.$store.state.loginTenant.account,
            status: "未读"
          })
          .then(response => {
            this.messages = response.data.data;
          })
          .catch(error => {
            console.log(error);
          });
      }
    },
    logout() {
      this.$confirm("确定要退出登录吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$store.commit("setIsLogin", false);
          this.$store.commit("setLoginTenant", null);
          this.$router.push(
            "/login",
            () => {},
            () => {}
          );
        })
        .catch(() => {});
    },
    filterHouses(category, item) {
      this.$set(this.activeFilters, category, item);
      console.log(this.activeFilters);
      this.getCity();
      this.transformFilters();
    },
    isActive(category, item) {
      return this.activeFilters[category] === item;
    },
    updateCategoryItems(categoryName, newItems) {
      const category = this.categories.find(cat => cat.name === categoryName);
      if (category) {
        category.items = newItems;
      }
    },
    getProvince() {
      this.newItems = [];
      this.$axios.post("area/province", { name: "" }).then(res => {
        if (res.data.code == 200) {
          this.newItems.push("不限");
          for (let i = 0; i < res.data.data.length; i++) {
            this.newItems.push(res.data.data[i].name);
          }
          this.updateCategoryItems("省份", this.newItems);
          this.getCity();
        }
      });
    },
    getCity() {
      this.newItems = [];
      let province = this.activeFilters["省份"];
      if (province == "不限" || province == undefined) {
        province = "";
      }
      this.$axios.post("area/city", { province, name: "" }).then(res => {
        if (res.data.code == 200) {
          this.newItems.push("不限");
          for (let i = 0; i < res.data.data.length; i++)
            this.newItems.push(res.data.data[i].name);
        }
        this.updateCategoryItems("城市", this.newItems);
        this.getAreaName();
      });
    },
    getAreaName() {
      this.newItems = [];
      let province = this.activeFilters["省份"];
      if (province == "不限" || province == undefined) {
        province = "";
      }
      let city = this.activeFilters["城市"];
      if (city == "不限" || city == undefined) {
        city = "";
      }
      this.$axios.post("area/query", { province, city, name: "" }).then(res => {
        if (res.data.code == 200) {
          this.newItems.push("不限");
          for (let i = 0; i < res.data.data.length; i++) {
            this.newItems.push(res.data.data[i].name);
          }
          this.updateCategoryItems("区域", this.newItems);
          this.getCommunity();
        }
      });
    },
    getCommunity() {
      this.newItems = [];
      let area = this.activeFilters["区域"];
      if (area == "不限" || area == undefined) {
        area = "";
      }
      this.$axios.post("community/get", { area, name: "" }).then(res => {
        if (res.data.code == 200) {
          this.newItems.push("不限");
          for (let i = 0; i < res.data.data.length; i++) {
            this.newItems.push(res.data.data[i].name);
          }
          this.updateCategoryItems("小区", this.newItems);
          this.getLayout();
        }
      });
    },
    getLayout() {
      this.newItems = [];
      let communityName = this.activeFilters["小区"];
      if (communityName == "不限" || communityName == undefined) {
        communityName = "";
      }
      let areaName = this.activeFilters["区域"];
      if (areaName == "不限" || areaName == undefined) {
        areaName = "";
      }
      this.$axios
        .post("apartment/layout", { communityName, areaName })
        .then(res => {
          if (res.data.code == 200) {
            this.newItems.push("不限");
            for (let i = 0; i < res.data.data.length; i++) {
              this.newItems.push(res.data.data[i]);
            }
            this.updateCategoryItems("户型", this.newItems);
            this.getArea();
          }
        });
    },
    getArea() {
      this.newItems = [];
      let communityName = this.activeFilters["小区"];
      if (communityName == "不限" || communityName == undefined) {
        communityName = "";
      }
      let areaName = this.activeFilters["区域"];
      if (areaName == "不限" || areaName == undefined) {
        areaName = "";
      }
      this.$axios
        .post("apartment/area", { communityName, areaName })
        .then(res => {
          if (res.data.code == 200) {
            this.newItems.push("不限");
            for (let i = 0; i < res.data.data.length; i++) {
              this.newItems.push(res.data.data[i]);
            }
            this.updateCategoryItems("面积", this.newItems);
            this.getRent();
          }
        });
    },
    getRent() {
      this.newItems = [];
      let communityName = this.activeFilters["小区"];
      if (communityName == "不限" || communityName == undefined) {
        communityName = "";
      }
      let areaName = this.activeFilters["区域"];
      if (areaName == "不限" || areaName == undefined) {
        areaName = "";
      }
      this.$axios
        .post("apartment/rent", { communityName, areaName })
        .then(res => {
          if (res.data.code == 200) {
            this.newItems.push("不限");
            for (let i = 0; i < res.data.data.length; i++) {
              this.newItems.push(res.data.data[i]);
            }
            this.updateCategoryItems("租金", this.newItems);
            this.getApartment();
          }
        });
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.getApartment();
    },
    handleCurrentChange(page) {
      this.currentPage = page;
      this.getApartment();
    },
    getApartment() {
      Object.entries(this.search).forEach(([key, value]) => {
        if (value == "不限") {
          this.search[key] = "";
        }
      });

      this.$axios
        .post("apartment/query", {
          ...this.search,
          size: this.pageSize,
          curr: (this.currentPage - 1) * this.pageSize,
          status: "已发布"
        })
        .then(res => {
          if (res.data.code == 200) {
            this.total = res.data.total;
            this.houses = [];
            res.data.data.forEach(item => {
              this.houses.push({
                id: item.id,
                name: item.areaName + item.communityName + item.roomNumber,
                image: item.image,
                rent: "￥" + item.monthlyRent + "元/月",
                other:
                  `${item.rooms}房${item.livingRooms}厅${item.bathrooms}卫${item.balconies}阳 | ` +
                  `${item.area}m²`,
                areaName: item.areaName,
                communityName: item.communityName,
                roomNumber: item.roomNumber
              });
            });
          }
        });
    },
    transformFilters() {
      const filters = this.activeFilters;
      const fieldMapping = {
        省份: "province",
        城市: "city",
        区域: "areaName",
        小区: "communityName",
        户型: "houseType",
        面积: "area",
        租金: "monthlyRent"
      };
      for (const [key, value] of Object.entries(filters)) {
        if (value !== undefined) {
          if (key === "户型") {
            const houseTypeDetails = this.splitHouseType(value);
            Object.assign(this.search, houseTypeDetails);
          } else {
            const englishKey = fieldMapping[key];
            if (englishKey) {
              this.search[englishKey] = value;
            }
          }
        }
      }
    },
    splitHouseType(houseType) {
      const regex = /(\d+)房(\d+)厅(\d+)卫(\d+)阳/;
      const matches = houseType.match(regex);
      if (matches) {
        return {
          rooms: parseInt(matches[1]),
          livingRooms: parseInt(matches[2]),
          bathrooms: parseInt(matches[3]),
          balconies: parseInt(matches[4])
        };
      }
      return {};
    },
    goToHouseDetail(areaName, communityName, roomNumber) {
      store.dispatch("setAreaName", areaName);
      store.dispatch("setCommunityName", communityName);
      store.dispatch("setRoomNumber", roomNumber);
      this.$router.push(
        "/houseDetail",
        () => {},
        () => {}
      );
    }
  }
};
</script>

<style scoped>
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  background-color: #f5f5f5;
}
.title {
  font-size: 24px;
  font-weight: bold;
  text-align: center;
  flex-grow: 1;
}
.auth-buttons {
  display: flex;
  gap: 10px;
}
.breadcrumb {
  padding: 10px;
  margin-left: 15px;
  margin-top: 10px;
}
.navigation-card {
  width: 94.5%;
  margin: 20px auto;
  padding: 20px;
  background-color: #fff;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.category {
  margin-bottom: 20px;
}
.items a {
  margin-right: 10px;
  text-decoration: none;
  color: #409eff;
  cursor: pointer;
}
.items a:hover,
.items a.active {
  color: #66b1ff;
  font-weight: bold;
}
.results {
  margin-left: 10px;
  margin-right: 10px;
  display: flex;
  flex-wrap: wrap;
}
.el-card {
  margin-top: 20px;
}
.image {
  width: 100%;
  display: block;
}
.bottom {
  margin-top: 13px;
  line-height: 12px;
}

.other {
  font-size: 13px;
  color: #999;
}
.button {
  float: right;
  padding: 0;
}
.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px;
}
</style>
